import orgCtrl from '../../../ts/controller'
import { kernel } from '../../../ts/base'

class Common {
  files: any[] = []

  async loadCommons(): Promise<any[]> {
    if (!orgCtrl.provider.user) return this.files
    if (this.files.length > 0) return this.files
    const promises = orgCtrl.provider.user.commons.map(async item => {
      const [queryWorkEntity, queryCompanyEntity] = await Promise.all([
        kernel.queryEntityById({ id: item.id }),
        kernel.queryEntityById({ id: item.spaceId })
      ])
      const workEntityMetaData = queryWorkEntity?.data
      const companyEntityMetaData = queryCompanyEntity?.data
      if (
        workEntityMetaData &&
        companyEntityMetaData &&
        workEntityMetaData.typeName === '办事'
      ) {
        const tags = [companyEntityMetaData.name, workEntityMetaData.typeName]
        const commonWork = {
          id: workEntityMetaData.id,
          applicationId: item.applicationId,
          belongId: companyEntityMetaData.id,
          title: workEntityMetaData.name,
          remark: workEntityMetaData.remark,
          comment: workEntityMetaData.remark,
          metadata: companyEntityMetaData,
          icon: workEntityMetaData.icon || '',
          groupTags: tags
        }
        return commonWork
      }
    })
    const results = await Promise.all(promises)
    this.files.push(...results.filter(Boolean))
    return this.files
  }

  /** 初始化 */
  async initPortal() {
    return await this.loadCommons()
  }

  clear() {
    this.files = []
  }
}

export default new Common()
